<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2018/2/12
 * Time: 22:06
 */

namespace app\models;


use app\librarys\Tools;
use app\librarys\ZfbService;
use app\models\db\MiniPrograms;
use app\models\db\TUser;
use yii\db\Query;

class MiniProgramsExt extends db\MiniPrograms
{

    /**
     * 数量
     * @param string $name
     * @return int|string
     */
    public static function getMiniProgramCount($name = '')
    {
        return db\MiniPrograms::find()
            ->where(['is_deleted'=>0])
            ->andFilterWhere(['like', 'name', $name])
            ->count();
    }


    /**
     * 列表
     * @param int $page
     * @param int $pageSize
     * @param string $name
     * @return mixed
     */
    public static function getMiniProgramList($page = 0, $pageSize = 20, $name = '')
    {
        if ($page <= 0) $page = 0;
        $start = $page * $pageSize;


        $items = db\MiniPrograms::find()
            ->where(['is_deleted'=>0])
            ->andFilterWhere(['like', 'name', $name])
            ->orderBy('create_datetime desc')
            ->limit($pageSize)
            ->offset($start)
            ->all();
        return $items;

    }

    /**
     *  根据id获取行
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getMiniProgramById($id)
    {
        $item = db\MiniPrograms::find()
            ->where(['id' => $id])
            ->one();
        return $item;
    }


    /**
     * save data
     * @param $id
     * @param $name
     * @param $raw_id
     * @param $app_id
     * @param $app_secret
     * @param $type
     * @param $begin_datetime
     * @param $end_datetime
     * @return bool
     */
    public static function saveMiniProgram($id, $name, $raw_id, $app_id, $app_secret, $type, $begin_datetime, $end_datetime, $is_enabled)
    {
        $item = self::getMiniProgramById($id);
        if (!$item) {
            $item = new db\MiniPrograms();
            $item->id = Tools::db_uuid();
            $item->is_deleted = 0;
        }

        $item->name = $name;
        $item->raw_id = $raw_id;
        $item->app_id = $app_id;
        $item->app_secret = $app_secret;
        $item->type = $type;
        $item->begin_datetime = $begin_datetime;
        $item->end_datetime = $end_datetime;
        $item->is_enabled = $is_enabled;

        $result = $item->save();

        return $result;
    }



    public static function deleteMiniProgram($id)
    {
        $item = self::getMiniProgramById($id);
        $item->is_deleted = 1;

        $result = $item->save();

        return $result;
    }
}